# -*- coding: utf-8 -*-
from django.contrib.comments.views.comments import CommentPostBadRequest 
from django.contrib.comments.views.utils import next_redirect
from django.contrib import comments
from django.contrib.comments import signals

from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect
from util.cache import expire_page
from django.utils.html import escape


def post_comment(request, next, target, context_dict, template):
	"""
	Post a comment. Modified from django source

	HTTP POST is required. If ``POST['submit'] == "preview"`` or if there are
	errors a preview template, ``comments/preview.html``, will be rendered.
	"""
	# Fill out some initial data fields from an authenticated user, if present
	data = request.POST.copy()

	# Do we want to preview the comment?
	preview = "preview" in data

	# Construct the comment form
	form = comments.get_form()(target, data=data)

	# Check security information
	if form.security_errors():
		return CommentPostBadRequest(
				"The comment form failed security verification: %s" % \
						escape(str(form.security_errors())))

	# If there are errors or if we requested a preview show the comment
	if form.errors:
		page_h1 = ""
		if target.__dict__.has_key("name"):
			page_h1 = target.name
		if target.__dict__.has_key("title"):
			page_h1 = target.title

		context_dict.update({"comment" : form.data.get("comment", ""), "form" : form, "page_h1": page_h1, "page_title": u"There was a problem saving your comment"})
		return render_to_response(template, context_dict)

	# Otherwise create the comment
	comment = form.get_comment_object()
	comment.ip_address = request.META.get("REMOTE_ADDR", None)
	if request.user.is_authenticated():
		comment.user = request.user

	# Signal that the comment is about to be saved
	responses = signals.comment_will_be_posted.send(
			sender  = comment.__class__,
			comment = comment,
			request = request
			)

	for (receiver, response) in responses:
		if response == False:
			return CommentPostBadRequest(
					"comment_will_be_posted receiver %r killed the comment" % receiver.__name__)

	# Save the comment and signal that it was saved
	comment.save()
	signals.comment_was_posted.send(
			sender  = comment.__class__,
			comment = comment,
			request = request
			)

	# Everything successful - Check where to go next
	next = target.get_absolute_url() + "?go#c" + str(comment._get_pk_val())

	# expire cache for target, start page and comment feed
	expire_page(next)
	expire_page("/")
	expire_page("/data/")

	return HttpResponseRedirect(next)

